<template>
    <el-drawer width="20vw" class="flex-drawer" direction="rtl" :close-on-click-modal="false" v-model="info.visible" @close="handleClose"  >
        <template #header>
            <div style="font-size:var(--18FontSize); font-weight:500; color:#525866;">{{ info.forEdit ? `编辑巡检对象(${info.row.templateCode})` : '新增巡检对象' }}</div>
        </template>
        <el-form class="flex-form" ref="myForm" :model="form" :rules="rules" label-position="top">
            <el-form-item label="巡检对象模板" prop="templateCode">
                <FlexSelect :payload="tplList" :data="tplOpt" :total="tplTotal" :form="form" :disabled="info.forEdit" @search="fetchTplList" />
            </el-form-item>
            <el-form-item label="名称" prop="targetName">
                <FlexInput :data="{ paramKey:'targetName' }" :form="form" />
            </el-form-item>
            <el-form-item label="位置" prop="attrId">
                <FlexTreeSelect :payload="attrList" :fieldMaps="{ label:'attrName', value:'attrId',  children:'subEnergyFieldAttr' }" :data="attrOpt" :form="form" />
            </el-form-item>
            <el-form-item v-if="tplInfo.templateCode" label="标签">
                <div>{{ labelInfo.labelName || '--' }}</div>
            </el-form-item>
            <el-form-item v-if="labelInfo.labelId === 1 " label="关联设备" prop="equipmentId">
                <FlexSelect :payload="machList" :data="machOpt" :total="machList.length" :form="form" />
            </el-form-item>
            <el-form-item label="分组" prop="groupId">
                <FlexSelect :payload="groupList" :data="groupOpt" :total="groupTotal" :form="form" />
            </el-form-item>  
            <el-form-item label="是否需要扫码开始检查" prop="needScan" class="flex-form-item">
                <FlexSwitch :data="{ paramKey:'needScan' }" :form="form" />
            </el-form-item>
        </el-form>
        <div style="display:flex; gap:var(--mPadding); margin-top:var(--lPadding); ">
            <div class="flex-btn middle opacity" style="flex:1;" @click="handleClose">取消</div>
            <div class="flex-btn middle" style="flex:1;" @click="handleSubmit">确认</div>
        </div>
    </el-drawer>
</template>

<script setup>
    import { watch, ref, reactive, computed, nextTick, onUnmounted, onMounted } from 'vue';
    import { getTplList, getLabelList } from '@/api/tpl.js';
    import { addOrUpdateObject } from '@/api/object.js';
    import { getFieldAttrs, getAttrMachList  } from '@/api/cycle.js';
    import { getGroupList } from '@/api/group.js';
    import FlexInput from '@/components/FlexInput.vue';
    import FlexSelect from '@/components/FlexSelect.vue';
    import FlexTreeSelect from '@/components/FlexTreeSelect.vue';
    import FlexSwitch from '@/components/FlexSwitch.vue';
    import { ElMessage } from 'element-plus';
    const props = defineProps({
        info:{ type:Object },
        labelList:{ type:Array },
        meterTypeList:{ type:Array }
    });
    const emit = defineEmits(['update:info', 'refresh']);
    const myForm = ref(null);
    
    let form = reactive({
        templateCode:'',
        targetName:'',
        attrId:'',
        equipmentId:'',
        groupId:'',
        needScan:false
    });
    const rules = reactive({
        templateCode:[{ required:true, message:'请选择巡检模板',  trigger:'blur' }],
        targetName:[{ required:true, message:'请输入名称',  trigger:'blur' }],
    });

    const tplList = ref([]);
    const tplTotal = ref(0);
    const tplOpt = { paramKey:'templateCode', labelName:'templateName', labelKey:'templateCode', fullWidth:true   };
    const attrList = ref([]);
    const attrOpt = { paramKey:'attrId', labelName:'attrName', labelKey:'attrId', fullWidth:true, hasPagination:true };
    const tplInfo = ref({});
    const machList = ref([]);
    const machOpt = { paramKey:'equipmentId', labelName:'meterName', labelKey:'machId', fullWidth:true, searchPlaceholder:'请输入设备名称查询', hasSearch:true, searchType:'local' };
    const groupList = ref([]);
    const groupOpt = { paramKey:'groupId', labelName:'groupName', labelKey:'groupId', fullWidth:true, hasPagination:true };
    const groupTotal = ref(0);
    const labelList = ref([]);
    const labelInfo = computed(()=>{
        return labelList.value.filter(i=>i.labelId === tplInfo.value.labelId)[0] || {};
    })
    // 重置状态
    function handleClose(){
        Object.keys(form).forEach(key=>{
            form[key] = key === 'needScan' ? false : '';
        })
        myForm.value.clearValidate();
        tplInfo.value = {};
        props.info.visible = false;
    }
    // watch(()=>form['targetName'], (prevVal, nextVal)=>{
    //     console.log('preVal...', prevVal);
    //     console.log('nextVal...', nextVal);
    // })
    watch([()=>form.templateCode, tplList], ()=>{
        //  获取模板的详情
        form.equipmentId = '';
        if ( form.templateCode ) {
            let obj = tplList.value.filter(i=>i.templateCode === form.templateCode)[0] || {};
            tplInfo.value = obj;
        }
    })
    watch([()=>form.attrId, tplInfo], ()=>{
        if ( tplInfo.value.equipmentType && form.attrId ) {
            fetchAttrMachList();
        }
    })
    function handleSubmit(){
        myForm.value.validate(valid=>{
            if ( valid ){   
                let obj = { ...form, needScan:form.needScan === true ? 1 : 0 };
                if ( props.info.forEdit ) {
                    obj.targetId = props.info.row.targetId;
                }
                addOrUpdateObject(obj, props.info.forEdit )             
                .then(res=>{
                    if ( res.data.code === 200 ) {
                        ElMessage({
                            type:'success',
                            message:`${props.info.forEdit ? '更新' : '新增'}巡检对象成功`
                        });
                        handleClose();
                        emit('refresh');
                    }
                })                                   
                
            }                      
        })
    }
    const fetchTplList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:999 };
		let realParams = {};
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		getTplList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				tplList.value = res.data.data;
			    tplTotal.value = res.data.total;
			}
		})
	};
    const fetchFieldAttrs = ()=>{     
        getFieldAttrs()
        .then(res=>{
            if ( res.data.code === 200 ){
                attrList.value = res.data.data;          
            }
        })                                 
    }
    const fetchAttrMachList = ()=>{
        getAttrMachList({ attrId:form.attrId, typeId:tplInfo.value.equipmentType })
        .then(res=>{
            if ( res.data.code === 200 ){
                machList.value = res.data.data;
            }
        })
    }
    const fetchLabelList = ()=>{
        getLabelList()
        .then(res=>{
            if ( res.data.code === 200 ) {
                labelList.value = res.data.data;
            }
        })
    }
    const fetchGroupList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:10 };
		let realParams = {};
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		getGroupList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				groupList.value = res.data.data;
				groupTotal.value = res.data.total;
			}
		})
	}
    watch(()=>props.info, ()=>{
        if ( props.info.visible ) {
            fetchTplList();
            fetchFieldAttrs();
            fetchLabelList();
            fetchGroupList();
        }
        // 编辑模式，填充表单
        if ( props.info.forEdit ) {
            console.log('forEdit...');
            let { templateCode, attrName, attrId, targetName, labelId, equipmentId, groupId, needScan   } = props.info.row;
            form.templateCode = Number(templateCode);
            form.targetName = targetName;
            form.attrId = attrId;
            form.labelId = labelId;
            form.equipmentId = equipmentId;
            form.groupId = groupId;
            form.needScan = Number(needScan) === 1 ? true : false;  
        }  
    })
   
</script>

<style lang="scss">
    
</style>